/*
 * Copyright 2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.paboo.chart.qrcode;

import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.qrcode.encoder.ByteMatrix;
import com.google.zxing.qrcode.encoder.Encoder;
import org.paboo.entity.ImageEntity;
import org.paboo.util.LoggerFactoryUtils;
import org.paboo.util.ZxingImage;

import java.awt.image.BufferedImage;
import java.nio.charset.StandardCharsets;
import java.util.EnumMap;
import java.util.Map;

/**
 * @author Leonard
 */
public class ZxingUtil {

    private static LoggerFactoryUtils logger = LoggerFactoryUtils.getInstance().load(ZxingUtil.class);

    public static ByteMatrix encode(QREntity p)
            throws WriterException {
        Map<EncodeHintType, Object> hints = new EnumMap<>(EncodeHintType.class);
        if (!StandardCharsets.ISO_8859_1.equals(p.getEncoding())) {
            // Only set if not QR code default
            hints.put(EncodeHintType.CHARACTER_SET, p.getEncoding());
        }
        return Encoder.encode(p.getData(), p.getEcLevel(), hints).getMatrix();
    }


    public static BufferedImage encodeWithImg(QREntity p)
            throws WriterException {
        ImageEntity img = new ImageEntity(p.getHeight(), p.getWidth(), p.getMargin(), p.getForegroundColor(), p.getBackgroundColor());
        logger.debug(img.toString());
        return ZxingImage.toBufferedImage(encode(p), img);
    }

    public static ErrorCorrectionLevel parseErrorCorrectLevel(String ecl) {
        if ("L".equals(ecl) || "l".equals(ecl)) {
            return ErrorCorrectionLevel.L;
        } else if ("Q".equals(ecl) || "q".equals(ecl)) {
            return ErrorCorrectionLevel.Q;
        } else if ("M".equals(ecl) || "m".equals(ecl)) {
            return ErrorCorrectionLevel.M;
        } else if ("H".equals(ecl) || "h".equals(ecl)) {
            return ErrorCorrectionLevel.H;
        } else {
            throw new IllegalArgumentException("invalid error correct level : " + ecl);
        }
    }
}
